<?php
declare (strict_types=1);

namespace app\model\admin;

use app\common\model\BaseModel;
use libs\JWT;

class User extends BaseModel
{
    protected $pk = 'id';
    protected $name = 'admin_user';

    protected function initialize()
    {
        parent::initialize();
    }

    /**
     * 获得列表
     * @param bool $where
     * @param string $fields
     * @param string|null $order
     * @param int $page
     * @param int $pageSize
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList($where = true, $fields = '*', $order = null, $page = 1, $pageSize = 20)
    {
        $data = [
            'count' => 0,
            'list' => []
        ];
        $count = $this->where($where)->count();
        if (empty($count)) {
            return $this->returnRight($data);
        }
        $order = is_null($order) ? $this->pk . ' desc' : $order;
        $list = $this->where($where)
            ->field($fields)
            ->order($order)
            ->page($page, $pageSize)
            ->select();
        $data['count'] = $count;
        $data['list'] = $list;
        return $this->returnRight($data);
    }

    /**
     * @param $data
     * @return array
     * 登录逻辑
     */
    public function doLogin($data)
    {
        $map = [
            'username' => $data['username'],
        ];
        $password = $this->where($map)->value('password');
        if (empty($password)) {
            return $this->returnError(1001);
        }
        $origin = authCode($password, 'DECODE', $this->salt, 0);
        if ($origin !== $data['password']) {
            return $this->returnError(1002);
        } else {
            $user['member_id'] = $this->where($map)->value('id');
            $jwt = new JWT();
            $token['token'] = $jwt->encode($user);
            return $this->returnRight($token);
        }
    }

    /**
     * @param $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 用户详情
     */
    public function getDetail($data)
    {
        $user = $this->where('id', $data['user_id'])->field('nickname,phone,username')
            ->find();
        return $this->returnRight($user);
    }
}
